#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <string.h>

#define UIFILE "ui.glade"
#define PREIMAGEFILE "pre.png"
#define PLAYIMAGEFILE "stop.png"
#define NEXTIMAGEFILE "next.png"
#define SOUNDMAGEFILE "sound.png"
#define BGIMAGEFILE "background.png"
#define WIDTH 800
#define HEIGHT 550
void btn_pre_song(AtkObject *object, gpointer user_data);
void btn_play_song(AtkObject *object, gpointer user_data);
void btn_next_song(AtkObject *object, gpointer user_data);
void func_btn_switch_sound(AtkObject *object, gpointer user_data);
void func_gtk_main_quit(AtkObject *object, gpointer user_data);
void func_btn_volume(AtkObject *object, gpointer user_data);

static int send_cmd_to_mplayer(int fd_cmd, char *cmd_str1, char *cmd_str2);
static int write_cmd_to_mplayer_fifo(int fd_cmd, char *cmd_str);
void init_song_list(char* path);
void change_song(int songIndex);
void *thread_1(void *arg);
void init_frame( GtkWidget  *window);
void load_css( void ); 
void set_song_time(); 
void *thread_2(void * arg);
gboolean timeout_callback(gpointer data);

int fds[2]; // 进程共享匿名管道
int fd=0;
int ispause=1; 	// 1:当前暂停 0:正常播放
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;// 互斥信号量
GtkLabel   *lable_player_name;//歌曲名称 
GtkVolumeButton *btn_Volume;//调节音量大小 
GtkProgressBar  *progress_bar; // 进度条
static char songDirs[10][100]={""}; //歌曲列表 
static int songlength=0; // 歌曲长度 
int  song_Index=0;//歌曲索引 


int main( int argc, char *argv[])
{
    GtkWidget  *window;

    gtk_init (&argc, &argv);
    load_css(); 
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_default_size(GTK_WINDOW(window), WIDTH, HEIGHT);
    gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
    gtk_window_set_title(window,"MP3 音乐播放器");
    init_song_list("./song");
	init_frame(window);
    gtk_widget_show_all(window);
    gtk_main();
    return 0;
}
void init_frame( GtkWidget  *window){
    GtkWidget  *fixedlayout; 
    GtkButton  *btn_pre_speed;  //快退
    GtkButton  *btn_pre;  //上一曲
    GtkButton  *btn_play; //播放
    GtkButton  *btn_next; //下一曲
    GtkButton  *btn_next_speed; //快进
    GtkButton  *btn_switch_sound; //声音开关
    GtkWidget  *imgaebackground;
    GtkWidget  *imagepre;
    GtkWidget  *imageplay;
    GtkWidget  *imagenext;
    GtkWidget  *imagesound;

    // 初始化界面
    fixedlayout = gtk_fixed_new();
    gtk_container_add(GTK_CONTAINER (window), fixedlayout);
    // 背景 image
    imgaebackground = gtk_image_new_from_file(BGIMAGEFILE);
    gtk_fixed_put(GTK_FIXED(fixedlayout), imgaebackground, 0, 0);
   

    // 初始化歌曲显示状态
	lable_player_name=gtk_label_new("");
	gtk_widget_set_size_request(lable_player_name, 80, 35);
	gtk_fixed_put(GTK_FIXED(fixedlayout), lable_player_name, 370, 80);
    char ls[100] ={"<span foreground='#EE00EE' font_desc='32'>"};
	 strcat(ls,songDirs[0]);
	 strcat(ls,"</span>");
	//setCss (lable_player_name, "lable_player_name{opacity:0.5}");
	gtk_label_set_markup(GTK_LABEL(lable_player_name),ls);

    /*
    btn_pre_speed = gtk_button_new_with_label("快退");
    gtk_widget_set_size_request(btn_pre_speed, 80, 35);
    gtk_fixed_put(GTK_FIXED(fixedlayout), btn_pre_speed, 0, 450);    */

       
    btn_pre = gtk_button_new_with_label("");//上一曲
    gtk_widget_set_size_request(btn_pre, 80, 35);
    gtk_fixed_put(GTK_FIXED(fixedlayout), btn_pre, 80, 450);

    btn_play = gtk_button_new_with_label("");//播放
    gtk_widget_set_size_request(btn_play, 80, 35);
    gtk_fixed_put(GTK_FIXED(fixedlayout), btn_play, 200, 450);

    btn_next = gtk_button_new_with_label("");//下一曲
    gtk_widget_set_size_request(btn_next, 80, 35);
    gtk_fixed_put(GTK_FIXED(fixedlayout), btn_next, 320, 450);
   /*
    btn_next_speed = gtk_button_new_with_label("快进");
    gtk_widget_set_size_request(btn_next_speed, 80, 35);
    gtk_fixed_put(GTK_FIXED(fixedlayout), btn_next_speed, 80, 450);    */

    btn_switch_sound = gtk_button_new_with_label("");//声音
    gtk_widget_set_size_request(btn_switch_sound, 80, 35);
    gtk_fixed_put(GTK_FIXED(fixedlayout), btn_switch_sound, 400, 450);

    // 初始化音量大小
	btn_Volume=gtk_volume_button_new (); 
    gtk_fixed_put(GTK_FIXED(fixedlayout), btn_Volume, 480, 460);
    gtk_scale_button_set_value(btn_Volume,(gdouble)0.5); 
    gtk_widget_set_focus_on_click (btn_Volume,(gboolean)-1);
    gtk_widget_set_name ( btn_Volume, "myScaleButton" );
    
    // 初始化进度条
	progress_bar = gtk_progress_bar_new();
	gtk_widget_set_size_request(progress_bar, 300, 40);
	gtk_fixed_put(GTK_FIXED(fixedlayout), progress_bar, 90, 500);
	g_timeout_add_seconds(100, timeout_callback, progress_bar);

    
    // 设置按钮透明
    gtk_button_set_relief(btn_pre,GTK_RELIEF_NONE);
    gtk_button_set_relief(btn_play,GTK_RELIEF_NONE);
    gtk_button_set_relief(btn_next,GTK_RELIEF_NONE);
    gtk_button_set_relief(btn_switch_sound,GTK_RELIEF_NONE);
    // 取消按钮焦点
    gtk_button_set_focus_on_click (btn_pre,(gboolean)1);
    gtk_button_set_focus_on_click (btn_play,(gboolean)1);
    gtk_button_set_focus_on_click (btn_next,(gboolean)1);
    gtk_widget_set_focus_on_click (window,(gboolean)1);
    // 按钮图片
    gint w=50;
    gint h=50;
    // 处理图片大小
    GdkPixbuf *src_pixbuf_pre = gdk_pixbuf_new_from_file(PREIMAGEFILE, NULL);	
	// w, h是指定图片的宽度和高度
	GdkPixbuf *dst_pixbuf_pre = gdk_pixbuf_scale_simple(src_pixbuf_pre, w, h, GDK_INTERP_BILINEAR);
    GdkPixbuf *src_pixbuf_next = gdk_pixbuf_new_from_file(NEXTIMAGEFILE, NULL);	

	GdkPixbuf *dst_pixbuf_next = gdk_pixbuf_scale_simple(src_pixbuf_next, w, h, GDK_INTERP_BILINEAR);
    GdkPixbuf *src_pixbuf_play = gdk_pixbuf_new_from_file(PLAYIMAGEFILE, NULL);	

	GdkPixbuf *dst_pixbuf_play = gdk_pixbuf_scale_simple(src_pixbuf_play, w, h, GDK_INTERP_BILINEAR);
    GdkPixbuf *src_pixbuf_sound = gdk_pixbuf_new_from_file(SOUNDMAGEFILE, NULL);
	GdkPixbuf *dst_pixbuf_sound = gdk_pixbuf_scale_simple(src_pixbuf_sound, w, h, GDK_INTERP_BILINEAR);

	imagenext =gtk_image_new();
	imageplay =gtk_image_new();
	imagepre =gtk_image_new();
	imagesound=gtk_image_new();

     // 处理普片资源
     gtk_image_set_from_pixbuf((GtkImage*)imagepre,dst_pixbuf_pre);
     gtk_image_set_from_pixbuf((GtkImage*)imageplay,dst_pixbuf_play);
     gtk_image_set_from_pixbuf((GtkImage*)imagenext,dst_pixbuf_next);
     gtk_image_set_from_pixbuf((GtkImage*)imagesound,dst_pixbuf_sound);
	 // 设置图片可见属性
     gtk_button_set_always_show_image(btn_play,TRUE);
     gtk_button_set_always_show_image(btn_pre,TRUE);
     gtk_button_set_always_show_image(btn_next,TRUE);
     gtk_button_set_always_show_image(btn_switch_sound,TRUE);

    // 设置图片资源
     gtk_button_set_image(btn_pre,imagepre);
     gtk_button_set_image(btn_play,imageplay);
     gtk_button_set_image(btn_next,imagenext);
     gtk_button_set_image(btn_switch_sound,imagesound);

    // 注册信号
    g_signal_connect_swapped(G_OBJECT(window), "destroy",G_CALLBACK(func_gtk_main_quit), NULL);
    g_signal_connect_swapped(G_OBJECT(btn_pre), "clicked",G_CALLBACK(btn_pre_song), NULL);
    g_signal_connect_swapped(G_OBJECT(btn_play), "clicked",G_CALLBACK(btn_play_song), NULL);
    g_signal_connect_swapped(G_OBJECT(btn_next), "clicked",G_CALLBACK(btn_next_song), NULL);
    g_signal_connect_swapped(G_OBJECT(btn_switch_sound), "clicked",G_CALLBACK(func_btn_switch_sound), NULL);
    g_signal_connect_swapped(G_OBJECT(btn_Volume), "value-changed",G_CALLBACK(func_btn_volume), NULL);

}
void func_gtk_main_quit(AtkObject *object, gpointer user_data){
    system("pkill mplayer");
	gtk_main_quit();
}
void func_btn_switch_sound(AtkObject *object, gpointer user_data){
	 send_cmd_to_mplayer(fd, "pause\n", NULL);
}
// 改变歌曲 
void change_song(int songIndex){
	 if(songIndex >= songlength){
	 	songIndex=0;
	 }
	 char s[100]={"loadfile "};
	 strcat(s,"song/"); 
	 strcat(s, songDirs[songIndex]);
	 strcat(s, "\n");
	 printf("%s",s);
	 write(fd, s, strlen(s));
	 char ls[100] ={"<span foreground='#EE00EE'  font_desc='32'>"};
	 strcat(ls, songDirs[songIndex]);
	 strcat(ls,"</span>");
	 gtk_label_set_markup(GTK_LABEL(lable_player_name), ls);
	 
}
void load_css ( void ){
    GtkCssProvider *provider;
    GdkDisplay     *display;
    GdkScreen      *screen;
    /// ***
    const gchar *css_style_file = "style.css";
    GFile *css_fp               = g_file_new_for_path ( css_style_file );
    GError *error               = 0;
    /// ***
    provider = gtk_css_provider_new ();
    display  = gdk_display_get_default ();
    screen   = gdk_display_get_default_screen ( display );
    /// ***
    gtk_style_context_add_provider_for_screen   ( screen, GTK_STYLE_PROVIDER ( provider ), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION );
    gtk_css_provider_load_from_file             ( provider, css_fp, &error );
    /// ***
}
void *thread_1(void *arg){
    while(1)
    {
        printf("this is my new thread1 var++\n");
        execlp("mplayer",
               " mplayer ",
               "-slave", "-quiet","-idle",
               "-input", "file=./fifo_cmd",
               "1.mp3", NULL);
        sleep(1);
    }
    return NULL;
}
void btn_pre_song(AtkObject *object, gpointer user_data){
       change_song(song_Index<=0?0:song_Index--);
}
void btn_play_song(AtkObject *object, gpointer user_data){

	pid_t pid = 0;
	pid = fork();
	if (pid <0)
	{
		perror("fork");
	}
	if(pipe(fds) == -1){
        perror("pipe error");
        exit(EXIT_FAILURE);
    }
	else if (pid == 0)//子进程
	{	
		    char s[100]={"song/"};
		    strcat(s,songDirs[0]);
		    execlp("mplayer", "mplayer", "-ac", "mad", "-slave", "-quiet", "-input", "file=./song_fifo", s, NULL);
		    ispause=0;
		    dup2(fd,fds[1]);
	}
	umask(0);
  	fd= mkfifo("./song_fifo",0777);
	fd = open("./song_fifo",  O_RDWR); // O_WRONLY  写 O_RDONLY);//只读且阻塞 O_CREAT | O_APPEND | O_RDWR
	//set_song_time();
}
void init_song_list(char* path){
    DIR    *dir;
    struct  dirent *ptr; 
    dir = opendir(path);
    while((ptr = readdir(dir)) != NULL){
	if(strlen(ptr->d_name)>3){
	    printf("d_name: %s\n", ptr->d_name);
	    sprintf(songDirs[songlength++],"%s",ptr->d_name);
      }
    }
    closedir(dir);
}
void btn_next_song(AtkObject *object, gpointer user_data){
	 change_song(song_Index>songlength?songlength-1:song_Index++);
}

static int write_cmd_to_mplayer_fifo(int fd_cmd, char *cmd_str){
	int length = 0;
	int flag = 0;

	pthread_mutex_lock(&mutex);
	//printf("cmd_str = [%s]\n", cmd_str);
	length = write(fd_cmd, cmd_str, strlen(cmd_str));
	if(length != strlen(cmd_str))
	{
		perror("write command error!");
		flag = -1;
	}
	pthread_mutex_unlock(&mutex);

	return flag;
}
int send_cmd_to_mplayer(int fd_cmd, char *cmd_str1, char *cmd_str2){
	int flag = 0;
	char cmd_str[300];
	bzero(cmd_str, sizeof(cmd_str));
	if((strcmp(cmd_str1, "pause\n") == 0)){

		if(ispause == 0)		// 1:当前暂停 0:正常播放
		{
			ispause = 1;
		}
		else if(ispause == 1)
		{
			ispause = 0;
		}

		sprintf(cmd_str, "%s", cmd_str1);
		flag = write_cmd_to_mplayer_fifo(fd_cmd, cmd_str);
	}
	else if((strcmp(cmd_str1, "loadfile ") == 0)||(strcmp(cmd_str1, "seek ") == 0)){
		sprintf(cmd_str, "%s%s", cmd_str1, cmd_str2);
		flag = write_cmd_to_mplayer_fifo(fd_cmd, cmd_str);
	}else{
		if(ispause == 0)
		{
			sprintf(cmd_str, "%s", cmd_str1);
			flag = write_cmd_to_mplayer_fifo(fd_cmd, cmd_str);
		}
	}
	usleep(400000);
	return flag;
}
void func_btn_volume(AtkObject *object, gpointer user_data){
	 gdouble x=gtk_scale_button_get_value (btn_Volume);
	 char s[100]={"volume "};
	 char t[10]={0};
	 sprintf(t,"%.0f",x*100);
	 strcat(s,t);
	 strcat(s," 1\n");
	 write(fd, s, strlen(s));
	 printf("%s\n",s);
}
void set_song_time(){
	/** 返回字符串 
	get_percent_pos
	ANS_PERCENT_POSITION=12
	*/
	//progress_bar
	pid_t pid = 0;
	pid = fork();
	if (pid <0)
	{
		perror("fork");
	}
	else if (pid == 0)//子进程
	{		
		/*
	    while(1){
 			//char s[100]={"get_percent_pos\n"};
 		//	write(fd, s, strlen(s));
			//char readbuf[1280]={0};
			//gtk_progress_bar_set_text(progress_bar,readbuf); 
		//	dup2(1,fds[1]);
			//write(fds[1], "java", strlen("java"));
		    //read(fds[0],readbuf,strlen(readbuf));
		//	printf("ssss%s\n",readbuf);
			// ANS_PERCENT_POSITION=12
		//	char dest[10] = {0};
			//strncpy(dest,readbuf+21,strlen(readbuf)-21);
			//printf("xxxxxxxxxxxxxxxxxxxxxxxxxxxx%s\n",readbuf);
			//gtk_progress_bar_set_text(progress_bar,readbuf); 
			//gtk_label_set_markup(GTK_LABEL(lable_player_name), readbuf);
		    gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(progress_bar), pppp);
		    pppp+=0.1;
			//printf("%s",s);
			usleep(1000000);
			//dup2(fd,1);
		 }
		 */
	}
		
}
gboolean timeout_callback(gpointer data) {
    gdouble value;
    GString *text;

    value = gtk_progress_bar_get_fraction(GTK_PROGRESS_BAR(data));

    value += 0.01;
    if(value > 1.0) {
        value = 0.0;
    }
	gdk_threads_enter();
    gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(data), value);

    text = g_string_new(
             gtk_progress_bar_get_text(GTK_PROGRESS_BAR(data)));
    g_string_sprintf(text, "%d %%", (int) (value * 100));

    gtk_progress_bar_set_text(GTK_PROGRESS_BAR(data), text->str);
    gdk_threads_leave();
    return TRUE;
}

void *thread_2(void * arg)
{
	
	return NULL;
}